from vcbrowser import settings
from vcbrowser.engine.base import VCBrowserError

import logging

def import_class(class_path):
    """
    Returns engine from the given path.
    """
    splitted = class_path.split('.')
    mod_path = '.'.join(splitted[:-1])
    class_name = splitted[-1]
    try:
        class_mod = __import__(mod_path, {}, {}, [class_name])
    except ImportError, err:
        msg = str(err)
        logging.error("There was problem while trying to import backend class. "
            "Original error was:\n%s" % msg)
        raise VCBrowserError(msg)
    cls = getattr(class_mod, class_name)
    
    return cls

def highlight_code(name, code, type='terminal'):
    """
    If pygments are available on the system
    then returned output is colored. Otherwise
    unchanged content is returned.
    """
    try:
        import pygments
    except ImportError:
        return content
    from pygments import highlight
    from pygments.lexers import guess_lexer_for_filename, ClassNotFound
    from pygments.formatters import TerminalFormatter

    try:
        lexer = guess_lexer_for_filename(name, code)
        formatter = TerminalFormatter()
        content = highlight(code, lexer, formatter)
    except ClassNotFound, err:
        logging.debug("Couldn't guess Lexer, will not use pygments.")
        content = code
    return content
    

